home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / gnu / tput-1_0.lha / tput-1.0 / bsearch.c next >
C/C++ Source or Header  |  1991-07-08  |  2KB  |  62 lines

  1. /* Copyright (C) 1991 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3.  
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Library General Public License as
  6. published by the Free Software Foundation; either version 2 of the
  7. License, or (at your option) any later version.
  8.  
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  12. Library General Public License for more details.
  13.  
  14. You should have received a copy of the GNU Library General Public
  15. License along with the GNU C Library; see the file COPYING.LIB.  If
  16. not, write to the Free Software Foundation, Inc., 675 Mass Ave,
  17. Cambridge, MA 02139, USA.  */
  18.  
  19. #ifdef STDC_HEADERS
  20. #include <stdlib.h>
  21. #else
  22. #define NULL 0
  23. #include <sys/types.h>
  24. #endif
  25.  
  26. /* Perform a binary search for KEY in BASE which has NMEMB elements
  27.    of SIZE bytes each.  The comparisons are done by (*COMPAR)().  */
  28. char *
  29. bsearch (key, base, nmemb, size, compar)
  30.      register char *key;
  31.      register char *base;
  32.      size_t nmemb;
  33.      register size_t size;
  34.      register int (*compar) ();
  35. {
  36.   register size_t l, u, idx;
  37.   register char *p;
  38.   register int comparison;
  39.  
  40.   l = 0;
  41.   u = nmemb - 1;
  42.   while (l <= u)
  43.     {
  44.       idx = (l + u) / 2;
  45.       p = (char *) (((char *) base) + (idx * size));
  46.       comparison = (*compar) (key, p);
  47.       /* Don't make U negative because it will wrap around.  */
  48.       if (comparison < 0)
  49.     {
  50.       if (idx == 0)
  51.         break;
  52.       u = idx - 1;
  53.     }
  54.       else if (comparison > 0)
  55.     l = idx + 1;
  56.       else
  57.     return (char *) p;
  58.     }
  59.  
  60.   return NULL;
  61. }
  62.